<?php
namespace app\command;

use app\model\OrdersModel;
use app\model\UserModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;

class batchOrderAftersales extends Command
{

    protected function configure()
    {
        $this->setName('更新物流轨迹')
            ->setDescription('批量退款脚本');
    }

    protected function execute(Input $input, Output $output)
    {
        // 执行你的脚本任务代码

        $ordersModel = new OrdersModel();
        $userModel = new UserModel();
        $orderList = $ordersModel->where("wx_pay_info","<>","NULL")->select()->toArray();
        foreach ($orderList as $order){
            $userInfo = $userModel->getUserInfoByUid($order["uid"]);
            $token = $userInfo["wx_openid"];
            $wx_pay_info = json_decode($order['wx_pay_info'],true);


            $response = $this->fastRefund($order["order_id"],$token);

           echo  $response;
        }


        die;
    }


    function fastRefund($orderId, $token, $apiUrl = "https://api.sit.onefishx.com/api/OrderAftersales/fastRefund") {
        // 构建 multipart/form-data 请求体
        $boundary = '----' . md5(time());
        $data = array(
            'order_id' => $orderId
        );

        $postFields = '';
        foreach ($data as $key => $value) {
            $postFields .= "--" . $boundary . "\r\n";
            $postFields .= "Content-Disposition: form-data; name=\"" . $key . "\"\r\n\r\n";
            $postFields .= $value . "\r\n";
        }
        $postFields .= "--" . $boundary . "--\r\n";

        // 初始化 cURL 会话
        $curl = curl_init();

        // 设置 cURL 选项
        curl_setopt_array($curl, [
            CURLOPT_URL => $apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $postFields,
            CURLOPT_HTTPHEADER => [
                "User-Agent: Apipost/8 (https://www.apipost.cn)",
                "Content-Type: multipart/form-data; boundary=" . $boundary,
                "token: " . $token
            ],
            CURLOPT_SSL_VERIFYPEER => false,  // 禁用 SSL 证书验证（仅限开发环境）
            CURLOPT_SSL_VERIFYHOST => false   // 禁用 SSL 主机验证（仅限开发环境）
        ]);

        // 执行 cURL 请求
        $response = curl_exec($curl);
        $err = curl_error($curl);

        // 关闭 cURL 会话
        curl_close($curl);

        // 返回响应或错误
        if ($err) {
            return "cURL Error #:" . $err;
        } else {
            return $response;
        }
    }

}